package beer.xz.beer.device.data.product

import android.content.Context
import android.util.Log
import beer.xz.beer.device.data.api.ApiConfig
import beer.xz.beer.device.data.api.Apis
import beer.xz.beer.device.data.channel.Channels
import com.google.gson.Gson
import java.math.BigDecimal

object Products {
    private val products: MutableMap<String, SimpleProductData> = mutableMapOf()

    suspend fun load(context: Context): Boolean {
        var result = true
        val file = context.getFileStreamPath("products.json")
        //for test
        file.delete()
        if (file.exists()) {
            Log.d("Products", "load from file")
            file.inputStream().bufferedReader().use { reader ->
                val json = reader.readText()
                val gson = Gson()
                products.clear()
                products.putAll(
                    gson.fromJson(
                        json, Map::class.java
                    ) as Map<String, SimpleProductData>
                )
            }
        } else {
            Log.d("Products", "load from api")
            Channels.getChannels().forEach {
                if (!products.containsKey(it.productId)) {
                    val resultData =
                        Apis.ProductService.queryProductWithPrice(ApiConfig.getCode(), it.productId)
                    if (resultData.success && resultData.data != null && resultData.data!!.prices.isNotEmpty()) {
                        products[it.productId] = resultData.data!!
                        save(context)
                    } else {
                        result = false
                    }
                }
            }
        }
        return result
    }

    fun getProduct(): SimpleProductData {
        return products.values.first()
    }

    private fun removeFile(context: Context) {
        val file = context.getFileStreamPath("products.json")
        file.delete()
    }

    private fun save(context: Context) {
        val gson = Gson()
        val json = gson.toJson(products)
        val file = context.getFileStreamPath("products.json")
        file.outputStream().bufferedWriter().use { writer ->
            writer.write(json)
        }
    }

}


data class SimpleProductPriceData(
    val productId: String,
    val specName: String,
    val price: BigDecimal,
    val capacity: Int,
)

data class SimpleProductData(
    val uid: String,
    val name: String,
    val imageUrl: String?,
    val enabled: Boolean,
    val remark: String?,
    val prices: List<SimpleProductPriceData>
)